package com.iseastar.login;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.shouhuobao.station.R;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import droid.frame.activity.title.TitleRes;
import droid.frame.utils.lang.Str;

/**
 * 忘记密码
 *
 * @author coffee <br>
 * 2016-10-28下午3:41:47
 */
public class PasswordForgetActivity extends BaseActivity2 implements View.OnClickListener {

    private EditText mRetrievePhone, mRetrieveCheckCode, mRetrievePasswordNew, mRetrievePasswordAgain;
    // 获取验证码
    private Button mGetCheckCodeButton, mCommitButton;

    private HashMap<String, String> codeMap = new HashMap<String, String>();

    @Override
    protected void findViewById() {
        setContentView(R.layout.password_forget);
        super.findViewById();
        getAppTitle().setTitle(new TitleRes(R.drawable.title_back, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getContext(), LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }
        }), new TitleRes("找回密码"), null);

        mRetrievePhone = (EditText) findViewById(R.id.retrieve_phone);
        mRetrievePhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 可以修改手机号, 但是必须等到60s以后才可以重新发送
                if (s.length() == 11 && recLen == 60) {
                    mGetCheckCodeButton.setEnabled(true);
                } else {
                    mGetCheckCodeButton.setEnabled(false);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mRetrieveCheckCode = (EditText) findViewById(R.id.retrieve_checkcode);
        mRetrievePasswordNew = (EditText) findViewById(R.id.retrieve_new_password);
        mRetrievePasswordAgain = (EditText) findViewById(R.id.retrieve_new_password_again);
        // 获取验证码
        mGetCheckCodeButton = (Button) findViewById(R.id.get_checkcode);
        mGetCheckCodeButton.setOnClickListener(this);
        // 提交，修改密码
        mCommitButton = (Button) findViewById(R.id.commit_retrieve);
        mCommitButton.setOnClickListener(this);

    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.send_verifyNum:
                cancelLoadingDialog();
                ReqResult<?> result = JSON.parser(msg.obj);
                if (checkLoginStatus(result)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            countDownStart();
                        }
                    });
                    // result有时为null
                    if (result.getResult() != null) {
                        String code = result.getResult().toString();
                        codeMap.put(loginPhone, code);
                    }
                } else {
                    showToast(result.getMessage());
                }
                return false;
            case MsgID.confirmVerifyNum:
                cancelLoadingDialog();
                ReqResult<UserBean> loginResult = JSON.parser(msg.obj, UserBean.class);
                if (checkLoginStatus(loginResult)) {
                    finish();
                } else {
                    showToast(loginResult.getMessage());
                }
                return false;
            default:
                return super.handleMessage(msg);
        }
    }

    private String loginPhone;
    private boolean isAlreadyGetCode = false;

    @Override
    public void onClick(View v) {
        int i = v.getId();
        switch (i) {
            case R.id.get_checkcode:

                // 获取验证码
                if (mRetrievePhone.getText().length() == 11) {
                    loginPhone = mRetrievePhone.getText().toString();
                    // TODO 获取验证码
                    AppHttp.getInstance().loginSMSVerifyNum(mRetrievePhone.getText().toString());
                    showLoadingDialog(null);
                    isAlreadyGetCode = true;
                } else {
                    showToast("手机号输入有误");
                }
                break;
            case R.id.commit_retrieve:
                loginPhone = mRetrievePhone.getText().toString();
                // 提交修改密码
                String phone = mRetrievePhone.getText().toString();
                if (Str.isEmpty(phone)) {
                    showToast("请输入手机号，获取验证码");
                    return;
                }

                if (Str.isEmpty(mRetrieveCheckCode.getText().toString())) {
                    if (isAlreadyGetCode) {
                        showToast("请输入验证码");
                    } else {
                        showToast("请获取验证码");
                    }
                    return;
                }

                if (Str.isEmpty(mRetrievePasswordNew.getText().toString())) {
                    showToast("请输入新密码");
                    return;
                }

                if (Str.isEmpty(mRetrievePasswordAgain.getText().toString())) {
                    showToast("请再次输入新密码");
                    return;
                }

                if (!mRetrievePasswordAgain.getText().toString().equals(mRetrievePasswordNew.getText().toString())) {
                    showToast("两次新密码输入不一致，请重新输入");
                    return;
                }

                // 提交
                AppHttp.getInstance().confirmVerifyNum(mRetrievePhone.getText().toString(), mRetrieveCheckCode.getText().toString(), mRetrievePasswordNew.getText().toString(),
                        mRetrievePasswordAgain.getText().toString());
                break;
            default:
                break;
        }
    }

    // ***************
    private int recLen = 60;
    private boolean isStart;
    private Runnable runnable = new Runnable() {
        public void run() {
            if (recLen == 1) {
                isStart = false;
                recLen = 60;
                mGetCheckCodeButton.setEnabled(true);
                mGetCheckCodeButton.setText("再次发送");
            }

            if (recLen == 59) {
                showToast("短信验证码已发出, 请注意查收!");
            }
            if (isStart) {
                recLen--;
                mGetCheckCodeButton.setText("发送中..." + recLen);
                getHandler().postDelayed(this, 1000);
            }
        }
    };

    private void countDownStart() {
        getHandler().postDelayed(runnable, 1000);
        isStart = true;
        mGetCheckCodeButton.setEnabled(false);
        mRetrieveCheckCode.requestFocus();
        InputMethodManager imm = (InputMethodManager) mRetrieveCheckCode.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    public Handler smsHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                mRetrieveCheckCode.setText(msg.obj.toString());
            }
        }

        ;
    };

    private BroadcastReceiver smsReceiver;
    private IntentFilter smsFilter;

    private void registerSmsReceiver() {
        smsFilter = new IntentFilter();
        smsFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        smsFilter.setPriority(Integer.MAX_VALUE);
        smsReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Object[] objs = (Object[]) intent.getExtras().get("pdus");
                for (Object obj : objs) {
                    byte[] pdu = (byte[]) obj;
                    SmsMessage sms = SmsMessage.createFromPdu(pdu);
                    String message = sms.getMessageBody();
                    String from = sms.getOriginatingAddress();
                    if (!TextUtils.isEmpty(from)) {
                        String code = patternCode(message);
                        if (!TextUtils.isEmpty(code)) {
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = code;
                            smsHandler.sendMessage(msg);
                        }
                    }
                }
            }
        };
        registerReceiver(smsReceiver, smsFilter);
    }

    /**
     * @param @param  patternContent
     * @param @return
     * @return String
     * @throws
     * @Title: 匹配短信中间的6个数字（验证码等）
     * @Description:
     */
    private String patternCode(String patternContent) {
        if (TextUtils.isEmpty(patternContent)) {
            return null;
        }
        Pattern p = Pattern.compile("(?<!\\d)\\d{4}(?!\\d)");
        Matcher matcher = p.matcher(patternContent);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

}
